package com.xiyu.service.framework.postOffice.protocol;

import com.xiyu.service.model.mailbox.account.MailboxAccount;
import com.xiyu.service.repository.mailbox.account.MailboxAccountRepository;
import com.xiyu.service.service.mailbox.MailboxMailErrorLogService;
import jakarta.annotation.Resource;
import jakarta.mail.*;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import static com.xiyu.service.errorCode.mailbox.PostOfficeErrorCode.POST_OFFICE_PASSWORD_ERROR;
import static com.xiyu.service.framework.exception.util.ServiceExceptionUtil.exception;
import static com.xiyu.service.errorCode.mailbox.PostOfficeErrorCode.*;

@Component
public class SmtpProtocol implements SendProtocol {

    private Map<Long, Transport> transportMap = new HashMap<>();

    @Resource
    MailboxAccountRepository mailboxAccountRepository;

    @Resource
    private MailboxMailErrorLogService mailboxMailErrorLogService;

    private Authenticator getAuth(String account, String password)  {
        return new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(account, password);
            }
        };
    }

    private Transport createTransport(MailboxAccount account) throws MessagingException {
        Transport transport;
        // 设置 SMTP 连接属性
        Properties smtpProps = new Properties();
        smtpProps.put("mail.smtp.auth", "true");
        smtpProps.put("mail.smtp.starttls.enable", account.isStarttls());
        smtpProps.put("mail.smtp.ssl.enable", account.isSendSecure());
        smtpProps.put("mail.smtp.host", account.sendAddress());
        smtpProps.put("mail.smtp.port", account.sendPort());

        Session session = Session.getInstance(smtpProps, getAuth(account.mailboxAccount(), account.mailboxPassword()));


        transport = session.getTransport("smtp");
        transport.connect(account.sendAddress(), account.mailboxAccount(), account.mailboxPassword());

        return transport;
    }

    public void initProtocol(){
        // 解决发送邮件 速度慢的问题
        System.getProperties().setProperty("mail.mime.address.usecanonicalhostname", "false");
        List<MailboxAccount> accounts = mailboxAccountRepository.findAll();
        for(MailboxAccount account : accounts){
            try {
                transportMap.put(account.id(), createTransport(account));
            }catch (Exception e){
                mailboxMailErrorLogService.saveMailErrorInfo(account.id(), 0L, 0L, "", e);
            }
        }
    }

    public void setSmtpProtocol(MailboxAccount account) throws MessagingException {
        transportMap.put(account.id(), createTransport(account));
    }


    public Transport getSmtpProtocol(MailboxAccount account) {
        Transport transport;
        if(!transportMap.containsKey(account.id())) {
            try {
                setSmtpProtocol(account);
            }catch (AuthenticationFailedException e) {
                mailboxMailErrorLogService.saveMailErrorInfo(account.id(), 0L, 0L, "", e);
                throw exception(POST_OFFICE_PASSWORD_ERROR);
            }catch (Exception e){
                mailboxMailErrorLogService.saveMailErrorInfo(account.id(), 0L, 0L, "", e);
                throw exception(POST_OFFICE_CONNECT_ERROR);
            }
        }
        transport = transportMap.get(account.id());

        if(!transport.isConnected()){
            try {
                transport.connect(account.sendAddress(), account.mailboxAccount(), account.mailboxPassword());
            } catch (MessagingException e) {
                e.printStackTrace();
                throw exception(POST_OFFICE_CONNECT_ERROR);
            }
        }
        return transport;

    }

}
